package com.excel.exceldemo.controller;


import com.alibaba.excel.EasyExcelFactory;
import com.excel.exceldemo.pojo.User;
import com.excel.exceldemo.service.UserService;
import com.excel.exceldemo.web.JsonResult;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/excel")
public class ExcelController
{
    @Autowired
    UserService userService;
    /*
      excel导入并保存数据到mysql
     */
    @PostMapping("/import")
    @ApiOperation("导入")
    public JsonResult importExcle(@RequestPart(value = "file") MultipartFile file) throws IOException {
     log.info("开始导入");
     userService.addUserBatch(file);
     return JsonResult.ok();
    }

    /*
     导出数据为excel文件
     */
    @ApiOperation("导出")
    @GetMapping("/outImport")
    public void importExcel(HttpServletResponse response) throws IOException {
        try{
            String fileName = "表格文件名.xlsx";
            List<User> data = userService.getUserList();
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            EasyExcelFactory.write(response.getOutputStream(), User.class)
                    .sheet("这是一张表名")
                    .doWrite(data);
            response.getOutputStream().flush();
        }finally {
            response.getOutputStream().close();
        }

    }
}
